import {
  deleteBlackList,
  getBlackList,
  getInitiationUserList,
  getNotInitiationUserList,
} from '@/services/MeetingService';
import { useModel } from '@@/exports';
import {
  AudioOutlined,
  CaretDownOutlined,
  LogoutOutlined,
  TeamOutlined,
  UserAddOutlined,
  UserDeleteOutlined,
  UserSwitchOutlined,
  VideoCameraFilled,
} from '@ant-design/icons';
import { Button, Input, Modal, Tabs, TabsProps, message } from 'antd';
import { useEffect, useState } from 'react';
import styles from './chairMeeting.less';

const ChairMeeting = (props: {
  meetingArgument: { meetingCode: string; meetingName: string };
}) => {
  const [attendedList, setAttendedList] = useState<
    {
      userId: string;
      userName: string;
      avatar: string;
      messageType: string;
      pullFlag: boolean;
      pushFlag: boolean;
      audioFlag: boolean;
      videoFlag: boolean;
      app: string;
      stream: string;
    }[]
  >([]);
  const [notAttendedList, setNotAttendedList] = useState<
    {
      userId: string;
      userName: string;
      avatar: string;
      messageType: string;
      pullFlag: boolean;
      pushFlag: boolean;
    }[]
  >([]);
  const [blackList, setBlackList] = useState<
    {
      userId: string;
      userName: string;
      avatar: string;
      blackWhiteStatus: string;
    }[]
  >([]);
  const userInfo = JSON.parse(localStorage.getItem('userInfo')!);
  const { meetingCode, meetingName } = props.meetingArgument;
  const { Search } = Input;
  const [modalPosition, setModalPosition] = useState({ top: 0, left: 0 });
  const [modalFlag, setModalFlag] = useState<boolean>(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const { peerServer } = useModel('global');
  const [searchValues, setSearchValues] = useState({
    id1: '',
    id2: '',
    id3: '',
  });

  const sendMessage = async (message: {}) => {
    window.tm!.ipcRenderer.send(
      'send-websocket-message',
      JSON.stringify(message),
    );
  };

  useEffect(() => {
    window.osn.on('getAttendedList', (event: any, result: any) => {
      setAttendedList(result.inviteUserList);
    });
  }, []);

  const getAttendedList = async (searchName: string) => {
    const initiationUserList = await getInitiationUserList(
      peerServer,
      searchName,
      meetingCode,
    );
    setAttendedList(initiationUserList.data);
    setModalFlag(true);
  };

  const getNotAttendedList = async (searchName: string) => {
    const notInitiationUserList = await getNotInitiationUserList(
      peerServer,
      searchName,
    );
    setNotAttendedList(notInitiationUserList.data);
    setModalFlag(true);
  };
  const getBlackSearchList = async (searchName: string) => {
    const blackSearchList = await getBlackList(peerServer, searchName);
    setBlackList(blackSearchList.data);
    setModalFlag(true);
  };

  const handleOk = () => {
    setIsModalVisible(false);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const showModal = (e: any) => {
    setIsModalVisible(true);
    const buttonRect = e.target.getBoundingClientRect();
    setModalPosition({ top: buttonRect.bottom, left: buttonRect.left });
  };

  const tabClick = async (key: string) => {
    if (key === 'alreadyAttended') {
      //已入会
      const initiationUserList = await getInitiationUserList(
        peerServer,
        '',
        meetingCode,
      );
      setAttendedList(initiationUserList.data);
      getAttendedList('');
    } else if (key === 'notAttended') {
      //未入会
      const notInitiationUserList = await getNotInitiationUserList(
        peerServer,
        '',
      );
      setNotAttendedList(notInitiationUserList.data);
    } else if (key === 'blacklist') {
      //黑名单
      const blackList = await getBlackList(peerServer, '');
      setBlackList(blackList.data);
    }
  };

  const inviteUser = async (
    userId: string,
    userName: string,
    avatar: string,
  ) => {
    //告知服务器通知人员进入会议
    const inviteUserMessage = {
      messageType: 'inviteUser',
      userIds: userId,
      userName: userName,
      avatar: avatar,
      meetingCode: meetingCode,
      meetingName: meetingName,
    };
    await sendMessage(inviteUserMessage);
    return true;
  };

  const items: TabsProps['items'] = [
    {
      key: 'alreadyAttended',
      label: '已入会',
      children: (
        <div style={{ height: 300, overflow: 'auto' }}>
          <Search
            value={searchValues.id1}
            placeholder="请搜索姓名"
            allowClear
            onChange={(e) => {
              setSearchValues({
                ...searchValues,
                ['id1']: e.target.value,
              });
            }}
            onSearch={(value, event, info) => {
              getAttendedList(value);
            }}
          />
          {attendedList.length > 0 &&
            attendedList?.map((attended, index) => {
              return (
                <div className={styles.formChildrenContent}>
                  <div className={styles.leftDiv}>
                    <img
                      src={attended.avatar}
                      className={styles.avatarStyle}
                    ></img>
                    <span>{attended.userName}</span>
                  </div>
                  <div className={styles.rightDiv}>
                    {!attended.pushFlag && (
                      <Button
                        type={'text'}
                        icon={<CaretDownOutlined />}
                        onClick={showModal}
                      ></Button>
                    )}
                    <Button
                      type={'text'}
                      icon={<VideoCameraFilled />}
                      onClick={async () => {
                        const inviteUserMessage = {
                          messageType: 'changeVideo',
                          userId: attended.userId,
                          userName: attended.userName,
                          videoFlag: !attended.videoFlag,
                          meetingCode: meetingCode,
                          meetingName: meetingName,
                        };
                        await sendMessage(inviteUserMessage);
                        if (attended.audioFlag) {
                          message.success('关摄像头成功');
                        } else {
                          message.success('开摄像头成功');
                        }
                        return true;
                      }}
                    ></Button>
                    <Button
                      type={'text'}
                      icon={<AudioOutlined />}
                      onClick={async () => {
                        const inviteUserMessage = {
                          messageType: 'changeAudio',
                          userId: attended.userId,
                          userName: attended.userName,
                          audioFlag: !attended.audioFlag,
                          meetingCode: meetingCode,
                          meetingName: meetingName,
                        };
                        await sendMessage(inviteUserMessage);
                        if (attended.audioFlag) {
                          message.success('静音成功');
                        } else {
                          message.success('解除静音成功');
                        }
                        return true;
                      }}
                    ></Button>
                    <Modal
                      open={isModalVisible}
                      onOk={handleOk}
                      onCancel={handleCancel}
                      mask={false}
                      footer={null}
                      width={130}
                      closable={false}
                      style={{
                        position: 'absolute',
                        top: modalPosition.top + 'px',
                        left: modalPosition.left - 130 + 'px',
                      }}
                      styles={{
                        content: {
                          paddingLeft: 0,
                          paddingRight: 0,
                          paddingTop: 3,
                          paddingBottom: 2,
                        },
                      }}
                    >
                      <Button
                        icon={<UserSwitchOutlined />}
                        type={'text'}
                        style={{
                          width: '100%',
                          display: 'flex',
                          alignItems: 'flex-start',
                        }}
                        onClick={async () => {
                          const inviteUserMessage = {
                            messageType: 'changeEmcee',
                            changeUserId: attended.userId,
                            changeUserName: attended.userName,
                            app: attended.app,
                            stream: attended.stream,
                            userId: userInfo.id,
                            userName: userInfo.userName,
                            meetingCode: meetingCode,
                            meetingName: meetingName,
                          };
                          await sendMessage(inviteUserMessage);
                          message.success('指定主持人成功');
                          return true;
                        }}
                      >
                        指定为主持人
                      </Button>
                      <Button
                        icon={<UserDeleteOutlined />}
                        type={'text'}
                        style={{
                          width: '100%',
                          display: 'flex',
                          alignItems: 'flex-start',
                        }}
                        onClick={() => {
                          getAttendedList(searchValues.id1);
                          message.success('移除成功');
                          return true;
                        }}
                      >
                        移除会议
                      </Button>
                    </Modal>
                  </div>
                </div>
              );
            })}
        </div>
      ),
    },
    {
      key: 'notAttended',
      label: '未入会',
      children: (
        <div style={{ height: 300, overflow: 'auto' }}>
          <Search
            value={searchValues.id2}
            allowClear
            placeholder="请搜索姓名"
            onChange={(e) => {
              setSearchValues({
                ...searchValues,
                ['id2']: e.target.value,
              });
            }}
            onSearch={(value, event, info) => {
              getNotAttendedList(value);
            }}
          />
          {notAttendedList.length > 0 &&
            notAttendedList?.map((notAttended, index) => {
              return (
                <div className={styles.formChildrenContent}>
                  <div className={styles.leftDiv}>
                    <img
                      src={notAttended.avatar}
                      className={styles.avatarStyle}
                    ></img>
                    <span>{notAttended.userName}</span>
                  </div>
                  <div className={styles.rightDiv}>
                    <Button
                      type={'text'}
                      icon={<UserAddOutlined />}
                      onClick={() => {
                        inviteUser(
                          notAttended.userId,
                          userInfo.userName,
                          notAttended.avatar,
                        );
                        getNotAttendedList(searchValues.id2);
                        message.success('邀请成功');
                      }}
                    ></Button>
                  </div>
                </div>
              );
            })}
        </div>
      ),
    },
    {
      key: 'blacklist',
      label: '黑名单',
      children: (
        <div style={{ height: 300, overflow: 'auto' }}>
          <Search
            allowClear
            value={searchValues.id3}
            placeholder="请搜索姓名"
            onChange={(e) => {
              setSearchValues({
                ...searchValues,
                ['id3']: e.target.value,
              });
            }}
            onSearch={(value, event, info) => {
              getBlackSearchList(value);
            }}
          />
          {blackList.length > 0 &&
            blackList?.map((black, index) => {
              return (
                <div className={styles.formChildrenContent}>
                  <div className={styles.leftDiv}>
                    <img
                      src={black.avatar}
                      className={styles.avatarStyle}
                    ></img>
                    <span>{black.userName}</span>
                  </div>
                  <div className={styles.rightDiv}>
                    <Button
                      type={'text'}
                      icon={<LogoutOutlined />}
                      onClick={async (event) => {
                        await deleteBlackList(
                          peerServer,
                          black.blackWhiteStatus,
                        );
                        getBlackSearchList(searchValues.id3);
                        message.success('移除成功');
                      }}
                    ></Button>
                  </div>
                </div>
              );
            })}
        </div>
      ),
    },
  ];

  const changeVolume = async (volumeFlag: boolean) => {
    const inviteUserMessage = {
      messageType: 'changeVolume',
      userId: userInfo.id,
      userName: userInfo.userName,
      audioFlag: volumeFlag,
      meetingCode: meetingCode,
      meetingName: meetingName,
    };
    await sendMessage(inviteUserMessage);
    if (volumeFlag) {
      message.success('全员解除清音成功');
    } else {
      message.success('全员静音成功');
    }
    return true;
  };
  return (
    <>
      <Button
        size={'large'}
        onClick={() => {
          getAttendedList('');
        }}
      >
        <TeamOutlined />
        主持会议
      </Button>
      <Modal
        title="主持会议"
        width={400}
        open={modalFlag}
        onCancel={() => {
          setModalFlag(false);
        }}
        footer={
          <div className={styles.formContent}>
            <Button
              onClick={() => {
                changeVolume(false);
              }}
            >
              全员静音
            </Button>
            <Button
              onClick={() => {
                changeVolume(true);
              }}
            >
              全员解除静音
            </Button>
          </div>
        }
      >
        <Tabs
          defaultActiveKey={'alreadyAttended'}
          accessKey={'alreadyAttended'}
          type="card"
          items={items}
          animated={true}
          onTabClick={(key, event) => {
            tabClick(key);
          }}
        />
      </Modal>
    </>
  );
};

export default ChairMeeting;
